import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Typography, Tag, Space, Button, Skeleton, message, Descriptions, Divider } from 'antd';
import { EditOutlined, DeleteOutlined, DownloadOutlined, ShareAltOutlined } from '@ant-design/icons';
import { getKnowledgeDetail, deleteKnowledge } from '../../api/knowledge';

const { Title, Paragraph } = Typography;

const KnowledgeDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [knowledge, setKnowledge] = useState<any>(null);

  useEffect(() => {
    if (id) {
      fetchKnowledgeDetail(id);
    }
  }, [id]);

  const fetchKnowledgeDetail = async (knowledgeId: string) => {
    try {
      setLoading(true);
      const res = await getKnowledgeDetail(knowledgeId);
      setKnowledge(res);
    } catch (error) {
      console.error('获取知识详情失败:', error);
      message.error('获取知识详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    try {
      if (id) {
        await deleteKnowledge(id);
        message.success('删除成功');
        navigate('/knowledge');
      }
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handleEdit = () => {
    navigate(`/knowledge/edit/${id}`);
  };

  const handleDownload = () => {
    if (knowledge?.fileUrl) {
      window.open(knowledge.fileUrl, '_blank');
    } else {
      message.warning('没有可下载的文件');
    }
  };

  const handleShare = () => {
    // 实现分享功能
    message.info('分享功能开发中...');
  };

  if (loading) {
    return (
      <Card>
        <Skeleton active avatar paragraph={{ rows: 10 }} />
      </Card>
    );
  }

  if (!knowledge) {
    return (
      <Card>
        <div style={{ textAlign: 'center' }}>
          <Title level={4}>未找到知识内容</Title>
          <Button type="primary" onClick={() => navigate('/knowledge')}>
            返回知识列表
          </Button>
        </div>
      </Card>
    );
  }

  return (
    <Card>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <Title level={2}>{knowledge.title}</Title>
        <Space>
          <Button icon={<EditOutlined />} onClick={handleEdit}>编辑</Button>
          <Button icon={<DeleteOutlined />} danger onClick={handleDelete}>删除</Button>
          <Button icon={<DownloadOutlined />} onClick={handleDownload}>下载</Button>
          <Button icon={<ShareAltOutlined />} onClick={handleShare}>分享</Button>
        </Space>
      </div>

      <Descriptions bordered column={2} size="small" style={{ marginBottom: 20 }}>
        <Descriptions.Item label="创建时间">{new Date(knowledge.createdAt).toLocaleString()}</Descriptions.Item>
        <Descriptions.Item label="更新时间">{new Date(knowledge.updatedAt).toLocaleString()}</Descriptions.Item>
        <Descriptions.Item label="文件类型">{knowledge.fileType || '无'}</Descriptions.Item>
        <Descriptions.Item label="查看次数">{knowledge.viewCount || 0}</Descriptions.Item>
      </Descriptions>

      {knowledge.tags && knowledge.tags.length > 0 && (
        <div style={{ marginBottom: 16 }}>
          <Space>
            <span>标签:</span>
            {knowledge.tags.map((tag: string) => (
              <Tag key={tag} color="blue">{tag}</Tag>
            ))}
          </Space>
        </div>
      )}

      {knowledge.description && (
        <>
          <Divider orientation="left">描述</Divider>
          <Paragraph>{knowledge.description}</Paragraph>
        </>
      )}

      {knowledge.content && (
        <>
          <Divider orientation="left">内容</Divider>
          <div className="knowledge-content">
            {knowledge.content}
          </div>
        </>
      )}

      {knowledge.fileUrl && (
        <>
          <Divider orientation="left">文件预览</Divider>
          <div className="file-preview">
            {knowledge.fileType && ['jpg', 'jpeg', 'png', 'gif'].includes(knowledge.fileType.toLowerCase()) ? (
              <img src={knowledge.fileUrl} alt={knowledge.title} style={{ maxWidth: '100%' }} />
            ) : knowledge.fileType === 'pdf' ? (
              <iframe src={knowledge.fileUrl} width="100%" height="600px" title={knowledge.title} />
            ) : (
              <div style={{ textAlign: 'center' }}>
                <Button type="primary" onClick={handleDownload}>下载文件查看</Button>
              </div>
            )}
          </div>
        </>
      )}
    </Card>
  );
};

export default KnowledgeDetailPage;